package com.financing.wap.service.weixin.service.impl;

import java.util.ResourceBundle;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.financing.wap.service.weixin.service.WeixinPayService;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPaySendRedpackRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRedpackQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPaySendRedpackResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;

/**
 * @author Binary Wang
 */
@Service("payService")
public class PayServiceImpl implements WeixinPayService {

	WxPayService wxPayService;
	
	@PostConstruct
	public void init() {
		WxPayConfig payConfig = new WxPayConfig();
		ResourceBundle resource = ResourceBundle.getBundle("wx");
		String appid = resource.getString("pay.appid");
		String mchId = resource.getString("pay.mchId");
		String mchKey = resource.getString("pay.mchKey");
		String keyPath = resource.getString("pay.keyPath");
		String subAppId = resource.getString("pay.subAppId");
		String subMchId = resource.getString("pay.subMchId");
		String notifyUrl = resource.getString("pay.notifyUrl");
		String tradeType = resource.getString("pay.tradeType");
		payConfig.setAppId(StringUtils.trimToNull(appid));
		payConfig.setMchId(StringUtils.trimToNull(mchId));
		payConfig.setMchKey(StringUtils.trimToNull(mchKey));
		payConfig.setSubAppId(StringUtils.trimToNull(subAppId));
		payConfig.setSubMchId(StringUtils.trimToNull(subMchId));
		payConfig.setKeyPath(keyPath);
		
		payConfig.setNotifyUrl(StringUtils.trimToNull(notifyUrl));
		payConfig.setTradeType(StringUtils.trimToNull(tradeType));
		
		// 可以指定是否使用沙箱环境
		payConfig.setUseSandboxEnv(false);
		wxPayService = new WxPayServiceImpl();
		wxPayService.setConfig(payConfig);
	}

	@Override
	public Object createOrder(WxPayUnifiedOrderRequest orderRequest) throws WxPayException {
		return wxPayService.createOrder(orderRequest);
	}

	@Override
	public WxPayOrderNotifyResult parseOrderNotifyResult(String xmlResult)
			throws WxPayException {
		return wxPayService.parseOrderNotifyResult(xmlResult);
	}

	@Override
	public WxPaySendRedpackResult sendRedpack(WxPaySendRedpackRequest request)
			throws WxPayException {
		return wxPayService.sendRedpack(request);
	}

	@Override
	  public WxPayRedpackQueryResult queryRedpack(String partnerTradeNo) throws WxPayException{
		return wxPayService.queryRedpack(partnerTradeNo);
	}

}
